package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.Provinces;
import com.ruoyi.system.domain.ProvincesLocalCache;
import com.ruoyi.system.mapper.ProvincesMapper;
import com.ruoyi.system.service.IProvincesService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述 省市区Service接口实现类
 * 作者 ZhangPing
 * 创建时间 2023/8/22 14:11
 */
@Service
public class ProvincesServiceImpl extends ServiceImpl<ProvincesMapper, Provinces> implements IProvincesService {

    @Autowired
    RedisCache redisCache;
    @Autowired
    ProvincesMapper provincesMapper;

    @Override
    public List<Provinces> getByDepth(Integer depth) {
        ProvincesLocalCache provinces = redisCache.getCacheObject("provinces");
        if (ObjectUtils.isEmpty(provinces)) {
            provinces = doReloadCache();
            redisCache.setCacheObject("provinces", provinces);
        }
        return provinces.getProvincesDepthMap().get(depth);
    }

    @Override
    public List<Provinces> getByParentId(Integer parentId) {
        ProvincesLocalCache provinces = redisCache.getCacheObject("provinces");
        if (ObjectUtils.isEmpty(provinces)) {
            provinces = doReloadCache();
            redisCache.setCacheObject("provinces", provinces);
        }
        return provinces.getProvincesMap().get(parentId);
    }

    protected ProvincesLocalCache doReloadCache() {
        ProvincesLocalCache provincesLocalCache = new ProvincesLocalCache();

        List<Provinces> list = provincesMapper.list(new Provinces());
        Map<Integer, List<Provinces>> provincesParentMap = list.stream().filter(x -> x.getParentId() != null).sorted(Comparator.comparing(Provinces::getCityCode))
                .collect(Collectors.groupingBy(Provinces::getParentId));
        Map<Integer, List<Provinces>> provincesDepthMap = list.stream().filter(x -> x.getDepth() != null).sorted(Comparator.comparing(Provinces::getCityCode))
                .collect(Collectors.groupingBy(Provinces::getDepth));
        provincesLocalCache.setProvincesMap(provincesParentMap);
        provincesLocalCache.setProvincesDepthMap(provincesDepthMap);
        provincesLocalCache.setProvincesDOList(list);
        return provincesLocalCache;
    }
}
